package com.ruoyi;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yangxuqi
 * @Date: 2022/11/17/9:24
 * @Description:
 */
public class ServerThread extends Thread{
    private Socket socket = null;
    private static final Logger log = LoggerFactory.getLogger(ServerThread.class);
    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            /*BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
            while (true) {
                //读取从客户端传来的信息
                String userInput = bufferedReader.readLine();
                if (!StringUtils.isEmpty(userInput)) {
                    if ("exit".equals(userInput)) {
                        System.out.println("退出连接通信	");
                        break;
                    }
                    String stringFromIOStream = getStringFromIOStream(socket.getInputStream());
                    System.out.println("接收内容：" + stringFromIOStream+"服务器时间"+LocalDateTime.now());
                }
            }*/
            byte[] bytes = readStream(socket.getInputStream(), 3000);
            String str = new String(bytes, "UTF-8");
            String jsonStr = StringUtils.formatJson(str);
            System.out.println("接收内容：" + jsonStr + "服务器时间" + LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取字节
     *
     * @param inStream
     * @param timeout
     * @return
     * @throws Exception
     */
    private byte[] readStream(InputStream inStream, int timeout) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        readStreamWithRecursion(output, inStream,timeout);
        output.close();
        int size = output.size();
        log.info("本次读取字节总数：" + size);
        return output.toByteArray();
    }
    /**
     * 递归读取流
     *
     * @param output
     * @param inStream
     * @param timeout
     * @return
     * @throws Exception
     */
    public void readStreamWithRecursion(ByteArrayOutputStream output, InputStream inStream, int timeout) throws Exception {
        long start = System.currentTimeMillis();
        while (inStream.available() == 0) {
            if ((System.currentTimeMillis() - start) >timeout) {//超时退出
                throw new SocketTimeoutException("超时读取");
            }
        }
        byte[] buffer = new byte[2048];
        int read = inStream.read(buffer);
        output.write(buffer, 0, read);
        int wait = readWait();
        long startWait = System.currentTimeMillis();
        boolean checkExist = false;
        while (System.currentTimeMillis() - startWait <= wait) {
            int a = inStream.available();
            if (a > 0) {
                checkExist = true;
                //            LogUtils.w("========还有剩余：" + a + "个字节数据没读");
                break;
            }

        }
        if (checkExist) {
            readStreamWithRecursion(output, inStream, timeout);
        }

    }
    /**
     * 二次读取最大等待时间，单位毫秒
     */
    protected int readWait() {
        return 100;
    }
}
